package com.miui.theme.custom.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miui.theme.custom.data.ConfigDataStore
import com.miui.theme.custom.utils.MySQLHelper
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

data class ColumnInfo(
    val field: String,
    val type: String,
    val isNull: String,
    val key: String,
    val default: String?,
    val extra: String
)

class TableDetailsViewModel(configDataStore: ConfigDataStore) : ViewModel() {

    private val _dataState = MutableStateFlow(DataState.Idle)
    val dataState = _dataState.asStateFlow()

    private val _columnsInfo = MutableStateFlow<List<ColumnInfo>>(emptyList())
    val columnsInfo = _columnsInfo.asStateFlow()

    private val _error = MutableStateFlow<String?>(null)
    val error = _error.asStateFlow()

    private lateinit var helper: MySQLHelper
    private val initializationJob: Job = viewModelScope.launch {
        val config = configDataStore.config.first()!!
        helper = MySQLHelper(config)
    }

    fun loadTableStructure(tableName: String) {
        viewModelScope.launch {
            initializationJob.join()
            _dataState.value = DataState.Loading

            // 使用 DESCRIBE 命令
            val result = helper.executeQuery("DESCRIBE $tableName")

            if (result.isSuccess) {
                val rs = result.getOrThrow()
                try {
                    val infoList = mutableListOf<ColumnInfo>()
                    while (rs.next()) {
                        infoList.add(
                            ColumnInfo(
                                field = rs.getString("Field"),
                                type = rs.getString("Type"),
                                isNull = rs.getString("Null"),
                                key = rs.getString("Key"),
                                default = rs.getString("Default"),
                                extra = rs.getString("Extra")
                            )
                        )
                    }
                    _columnsInfo.value = infoList
                    _dataState.value = DataState.Success
                } catch (e: Exception) {
                    _error.value = "解析失败: ${e.message}"
                    _dataState.value = DataState.Error
                }
            } else {
                _error.value = "查询失败: ${result.exceptionOrNull()?.message}"
                _dataState.value = DataState.Error
            }
        }
    }
}